$: << File.join(File.expand_path(File.dirname(__FILE__)), "util")
require 'rubygems'
require 'optparse'
require 'OptionParserUtil'

class EasyHadoop
	attr_reader :optparse, :options, :arguments, :mandatory
	
	def initialize(arguments)
		@optparse = OptionParser.new
		@options = {}
		
		set_arguments(arguments)
		set_commands
		set_mandatory
		validate
	end
	
	def set_arguments(arguments)
		return if(arguments.nil?)
			
			
		if(arguments.is_a?(String))
			@arguments = arguments.split(/\s{1,}/)
		elsif(arguments.is_a?(Array))
			@arguments = arguments
		else 
			raise Exception, "Expecting String or Array of arguments. Found #{arguments.class}"
		end	
		
	end
	
	def set_mandatory
		@mandatory = []
		@mandatory << :input_delimiter
		@mandatory << :output_delimiter
		@mandatory << :debug
	end
	
	def set_commands
		@optparse.banner = "Usage: ruby #{$0}"
		@optparse.on('-h','--help','Display help screen'){puts @optparse; exit}
		
		@options[:debug] =false
		@optparse.on('-d','--debug','Debug Script'){@options[:debug]=true}
		
		@options[:input_delimiter]="\t"
		@optparse.on('--input-delimiter DELM', 'delimiter between columns in the input data'){|opt|
			#TODO: figure out way to specify tab
			@options[:input_delimiter]=OptionParserUtil.handle_delimiter(opt, "\t")
		}
		
		@options[:output_delimiter]="\t"
		@optparse.on('--output-delimiter DELM', 'delimiter between columns while printing data'){|opt|
			@options[:output_delimiter]=OptionParserutil.handle_delimiter(opt, "\t")
		}
		
		@options[:ignore] = true
		@optparse.on('--[no-]ignore', "Raise exception on faulty input"){|opt|
			@options[:ignore] = opt
		}
		
	end
	
	def validate()
		begin
			@optparse.parse!(@arguments) if @arguments

			missing = @mandatory.select{|param| @options[param].nil? }
            if not missing.empty?
      			puts "Missing Options: #{missing.join(', ')}"
      		    puts @optparse
      		    exit
      	    end
		rescue OptionParser::ParseError, OptionParser::InvalidArgument, OptionParser::InvalidOption, OptionParser::MissingArgument
			puts $!.to_s
      		puts @optparse
      		exit
		end
		@options.each{|k,v| puts "#{k}==>#{v.inspect}"} if(@options[:debug])
	end
end

# Scripting Option
if __FILE__ == $0
    cls = EasyHadoop.new(ARGV)
end